<template>
  <div class="lgin-page">
    <div class="title">
      <h3>登录界面</h3>
    </div>
    <el-form
      ref="formRef"
      :model="valueForm"
      :rules="rules"
    >
      <el-form-item prop="username">
        <el-input prefix-icon="User" placeholder="请输入用户名" v-model="valueForm.username"/>
      </el-form-item>
       <el-form-item prop="password">
        <el-input prefix-icon="Key" placeholder="请输入用密码" type="password" v-model="valueForm.password" show-password/>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit(formRef)">登录</el-button>
      </el-form-item>
    </el-form>
  </div>


</template>

<script setup>
import { onMounted, reactive, ref} from "vue"
import { useUsersStore } from '@/stores/user.js'
import { ElMessage } from 'element-plus'
import router from '@/router'

const userStrore = useUsersStore()
const formRef = ref()
const valueForm = reactive({
  username: '',
  password: ''
})
/* 用户名校验规则 */
const validateUsername = (rule, value, callback) => {
  if (!value) {
    return callback(new Error('用户名不能为空'))
  }
  if (value.length < 4) {
    return callback(new Error('用户名不少于4位'))
  }
  if (!/^[A-Za-z0-9]+$/.test(value)) {
    return callback(new Error('用户名只能包含字母和数字'))
  }
  callback()
}
/* 密码校验规则 */
const validatePassword = (rule, value, callback) => {
  if (!value) {
    return callback(new Error('密码不能为空'))
  }
  if (value.length < 6) {
    return callback(new Error('密码长度不能小于6位'))
  }
  if (!/(?=.*[A-Za-z])(?=.*\d)/.test(value)) {
    return callback(new Error('密码必须同时包含字母和数字'))
  }
  callback()
}
const rules = reactive({
  username: [{ validator: validateUsername, trigger: 'blur' }],
  password: [{ validator: validatePassword, trigger: 'blur' }]
})

const onSubmit = (formRef) => {
  if (!formRef) return
  formRef.validate((valid) => {
    if (valid) {
      console.log(valueForm)
      userStrore.userLogin(valueForm).then(() => {
        ElMessage.success("登录成功")
        router.push('/')
      }).catch(() => ElMessage.error("登录失败"))
    } else {
      console.log('error submit!')
    }
  })
}
</script>

<style lang="scss" scope>
.lgin-page {
  width: 400px;
  height: 300px;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  h3 {
    text-align: center;
    padding: 20px;
  }
  .el-button {
    width: 100%;
  }
}
</style>
